package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"strconv"
	"strings"
	"time"
)

const (
	HZ          = 100.0
	CPUACCTFILE = "/sys/fs/cgroup/cpu,cpuacct/cpuacct.stat"
)

func parseCPUacct(cpuacct string) []int {
	cpuinfoSlice := []int{}
	f, err := ioutil.ReadFile(cpuacct)
	if err != nil {
		fmt.Printf("read to fd fail\n")
	}
	c := strings.Split(string(f), "\n")
	for _, v := range c {
		r := strings.Trim(v, "usersystem")
		z := strings.ReplaceAll(string(r), " ", "")
		if z != "" {
			rr, _ := strconv.Atoi(z)
			// fmt.Printf("%T\n", rr)
			cpuinfoSlice = append(cpuinfoSlice, rr)
		}

	}
	return cpuinfoSlice
}

func main() {
	res1 := parseCPUacct(CPUACCTFILE)
	var user_1, system_1 int
	user_1 = res1[0]
	system_1 = res1[1]
	t := flag.String("t", "1", "-t opention, default 1s")
	flag.Parse()
	et, _ := strconv.Atoi(*t)
	time.Sleep(time.Duration(et) * time.Second)
	res2 := parseCPUacct(CPUACCTFILE)
	var user_2, system_2 int
	user_2 = res2[0]
	system_2 = res2[1]
	// fmt.Printf("user1 %v\n", user_1)
	// fmt.Printf("user2 %v\n", user_2)
	// fmt.Printf("system1 %v\n", system_1)
	// fmt.Printf("system2 %v\n", system_2)
	fmt.Printf("time %vs\n", et)
	var cpuUsage float32
	cpuUsage = (float32(user_2-user_1) + float32(system_2-system_1)) / (HZ * float32(et) * 1) * 100.0
	fmt.Printf("The container's cpu usage: %.2f%% \n", cpuUsage)
}
